<template>
    <div style="min-height:540px;">
        <CardTitle 
            :titles="cardTitleParam.titles" 
            :cardBgColor="cardTitleParam.cardBgColor" 
            @addFrom="openAddDialog"
        />
        <CardList :cardList="cardListParam.cardList" 
            :listField="cardListParam.listField"
            :operates="cardListParam.operates" 
            @editUser="openEditDialog"
            @delUser="openDelDialog"
        />
    </div>
    <!-- 新增配置 -->
    <el-dialog v-model="addDialogFormVisible" title="新增用户">
        <el-form ref="addFromRef" :model="addFrom.form" :rules="addFrom.form_rules" label-width="70px">
            <el-form-item label="姓名" prop="realName">
                <el-input v-model="addFrom.form.realName" placeholder="请输入姓名" />
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input type="password" show-password v-model="addFrom.form.password" placeholder="请输入密码" />
            </el-form-item>
            <el-form-item label="确认密码" prop="passwords">
                <el-input type="password" show-password v-model="addFrom.form.passwords" placeholder="请输入确认密码" />
            </el-form-item>
            <el-form-item label="手机号" prop="mobile">
                <el-input type="mobile" v-model="addFrom.form.mobile" placeholder="请输入手机号" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="addDialogFormVisible = false">取消</el-button>
                <el-button type="primary" :disabled="addFrom.submit_button_disabled" :loading="addFrom.submit_button_loading" @click="addUser(addFromRef)">确认</el-button>
            </span>
        </template>
    </el-dialog>

    <!-- 编辑配置 -->
    <el-dialog v-model="editDialogFormVisible" title="修改用户">
        <el-form ref="ruleEditFormRef" :model="editObj.form" :rules="editObj.form_rules" label-width="70px">
            <el-form-item label="用户ID" prop="id">
                <el-input :disabled="true" v-model="editObj.form.id" />
            </el-form-item>
            <el-form-item label="姓名" prop="realName">
                <el-input :disabled="realNameVisible" v-model="editObj.form.realName" />
            </el-form-item>
            <el-form-item v-if="pwdVisible" label="密码" prop="password">
                <el-input type="password" show-password v-model="editObj.form.password" />
            </el-form-item>
            <el-form-item v-if="pwdVisible" label="确认密码" prop="passwords">
                <el-input type="password" show-password v-model="editObj.form.passwords" />
            </el-form-item>
            <el-form-item label="手机号" prop="mobile">
                <el-input type="mobile" v-model="editObj.form.mobile" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="editDialogFormVisible = false">取消</el-button>
                <el-button type="primary" :loading="editObj.submit_button_loading" :disabled="editObj.submit_button_disabled" @click="editUser(ruleEditFormRef)">确认</el-button>
            </span>
        </template>
    </el-dialog>

     <!-- 删除配置 -->
     <el-dialog v-model="delDialogFormVisible" title="确定删除该用户吗？">
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="delDialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="delUser">确认</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script lang="ts" setup>
    import { reactive, ref, onMounted ,computed} from 'vue'
    import { ElMessage, FormInstance} from 'element-plus'
    import CardTitle from '@/components/CardTitle.vue';
    import CardList from '@/components/CardList.vue';
    import { validate_email, validate_password, validate_mobile } from "/src/utils/validate";
    import { AddUser as addUserReq, List as userListReq,DeleteUser as delUserReq,GetById,UpdateUser} from "/src/api/account";
    import desPwd from "/src/utils/kjax.des";

    const addDialogFormVisible = ref(false)
    const editDialogFormVisible = ref(false)
    const delDialogFormVisible = ref(false)

    const addFromRef = ref<FormInstance>()

    const ruleEditFormRef = ref<FormInstance>()

    const cardTitleParam = reactive({
        cardBgColor: "rgb(255, 208, 75)",
        titles: [
            { 'title': '用户ID'},
            { 'title': '姓名' },
            { 'title': '手机号' },
            // { 'title': '邮箱' },
            { 'title': '新增', 'type': 'button' }
        ]
    })
    const cardListParam = reactive({
        cardList: [],
        listField: ['id','realName', 'mobile'],
        operates: [
            { 'opeateName': '修改', 'opeateMethod': 'editUser' },
            { 'opeateName': '删除', 'opeateMethod': 'delUser' }
        ],
    })
      const dataUser = reactive({
        id:''
    })
    
    onMounted(() => {
        queryList();
    })
    
    // 查询列表
    const queryList = () => {
        userListReq()
            .then((res) => {
                if(res.code === 200){
                    cardListParam.cardList = res.data.content;
                }else{
                    ElMessage({
						message: res.msg||'获取用户列表失败.',
						type: "eror",
					});
                }
            });
    }

    const validate_name_rules = (rule, value, callback) => {
		if (value === "") {
			callback(new Error("请输入姓名"));
		}else {
			callback();
		}
	};
    // 校验手机号
	const validate_mobile_rules = (rule, value, callback) => {

		let regMobile = validate_mobile(value);
		if (value === "") {
			callback(new Error("请输入手机号"));
		} else if (!regMobile) {
			// callback(new Error("请输入>=6并且<=20位的密码，包含数字、字母"));
			callback(new Error("手机号不合法"));
		} else {
			callback();
		}
	};
	// 校验密码
	const validate_password_rules = (rule, value, callback) => {
		let regPassword = validate_password(value);
		if (value === "") {
			callback(new Error("请输入密码"));
		} else if (!regPassword) {
			// callback(new Error("请输入>=6并且<=20位的密码，包含数字、字母"));
			callback(new Error("请输入>=8并且<=20位的密码，包含数字、小写字母、大写字母、特殊字符 )(#?!@$%^&*-"));
		} else {
            addFromRef.value.validateField('passwords', () => null);
			callback();
		}
	};
	// 校验确认密码
	const validate_passwords_rules = (rule, value, callback) => {
		
		let regPassword = validate_password(value);
		// 获取“密码”
		const passwordValue = addFrom.form.password;
		if (value === "") {
			callback(new Error("请输入密码"));
		} else if (!regPassword) {
			// callback(new Error("请输入>=6并且<=20位的密码，包含数字、字母"));
            callback(new Error("请输入>=8并且<=20位的密码，包含数字、小写字母、大写字母、特殊字符 )(#?!@$%^&*-"));
		} else if (passwordValue && passwordValue !== value) {
			callback(new Error("两次密码不一致"));
		} else {
			callback();
		}
	};

    // 打开新增对话框
    const openAddDialog = () => {
        //打开弹出框
        addDialogFormVisible.value = true
    }
    
    // 新增用户
    const addFrom = reactive({
		form_rules: {
			realName: [{ validator: validate_name_rules, trigger: "change" }],
			password: [{ validator: validate_password_rules, trigger: "change" }],
			passwords: [{ validator: validate_passwords_rules, trigger: "change" }],
            mobile: [{ validator: validate_mobile_rules, trigger: "change" }],
		},
		form: {
			realName: "", // 用户名
			password: "", // 密码
			passwords: "", // 确认密码
			mobile: "", // 手机号
		},
		// 提交按钮
		submit_button_disabled: false,
        submit_button_loading:false,
	});

    // 新增配置
    const addUser = (formEl: FormInstance | undefined) => {

        if(addFrom.form.realName === ''){
			ElMessage({
                message: '请输入姓名！',
                type: 'error',
            })
            return false;
		}
        if(addFrom.form.password === ''){
			ElMessage({
                message: '请输入密码！',
                type: 'error',
            })
            return false;
		}

        if(!validate_password(addFrom.form.password)){
            ElMessage({
                message: '请输入>=8并且<=20位的密码，包含数字、小写字母、大写字母、特殊字符 )(#?!@$%^&*-！',
                type: 'error',
            })
            return false;
        }

        if(addFrom.form.password != addFrom.form.passwords){
			ElMessage({
                message: '两次密码输入不一致！',
                type: 'error',
            })
            return false;
		}

        if(addFrom.form.mobile === ''){
			ElMessage({
                message: '请输入手机号！',
                type: 'error',
            })
            return false;
		}

        if(!validate_mobile(addFrom.form.mobile)){
            ElMessage({
                message: '手机号不合法！',
                type: 'error',
            })
            return false;
        }

        const requestData = {
			realName: addFrom.form.realName,
			password: desPwd.getDes(addFrom.form.password.trim(), 'kingdom'),
			mobile: addFrom.form.mobile
		};
        addFrom.submit_button_loading = true;
        addFrom.submit_button_disabled = true;
        // console.log('提交新增用户');
        addUserReq(requestData)
			.then((res) => {
                if(res.code === 200){
                    addFrom.submit_button_loading = false;
                    addFrom.submit_button_disabled = false;
                    ElMessage({
                        message: '添加用户成功！',
                        type: 'success',
                    });
                    addDialogFormVisible.value = false;
                    queryList();
                    if (formEl) formEl.resetFields();
                }else{
                    ElMessage({
                        message: res.msg || '添加用户异常.',
                        type: 'error',
                    });
                    addFrom.submit_button_loading = false;
                    addFrom.submit_button_disabled = false;
                }
			})
			.catch((error) => {
				console.log("登录失败", error);
				addFrom.submit_button_loading = false;
                addFrom.submit_button_disabled = false;
			});
    }

    const validate_password_rules_u = (rule, value, callback) => {
        let regPassword = validate_password(value);
        if(value){
            if (!regPassword) {
                // callback(new Error("请输入>=6并且<=20位的密码，包含数字、字母"));
                callback(new Error("请输入>=8并且<=20位的密码，包含数字、小写字母、大写字母、特殊字符 )(#?!@$%^&*-"));
            } else {
                ruleEditFormRef.value.validateField('passwords', () => null);
                callback();
            }
        }else{
            ruleEditFormRef.value.validateField('passwords', () => null);
            callback();
        }
	};
	// 校验确认密码
	const validate_passwords_rules_u = (rule, value, callback) => {
		
		let regPassword = validate_password(value);
		// 获取“密码”
		const passwordValue = editObj.form.password;

        if(value){
            if(!regPassword) {
                // callback(new Error("请输入>=6并且<=20位的密码，包含数字、字母"));
                callback(new Error("请输入>=8并且<=20位的密码，包含数字、小写字母、大写字母、特殊字符 )(#?!@$%^&*-"));
            }else if (passwordValue !== value) {
			    callback(new Error("两次密码不一致"));
            }else{
                callback();
            }
        }else{
            if(passwordValue){
                callback(new Error("两次密码不一致"));
            }else{
                callback();
            }
        }
	};

     // 修改配置表单变量
     const editObj = reactive({
        form_rules: {
			realName: [{ validator: validate_name_rules, trigger: "change" }],
			password: [{ validator: validate_password_rules_u, trigger: "change" }],
			passwords: [{ validator: validate_passwords_rules_u, trigger: "change" }],
            mobile: [{ validator: validate_mobile_rules, trigger: "change" }],
		},
        form:{},
        submit_button_disabled:false,
        submit_button_loading: false
    })

    

    // 打开修改对话框
    const openEditDialog = (id) => {
        // 查询待修改数据
        GetById(id)
            .then((res) => {
                if(res.code === 200){
                    // 编辑数据设置
                    editObj.form = res.data
                    delete editObj.form.password;
                    // editObj.form.passwords = res.data.password;
                    // 打开弹出框
                    editDialogFormVisible.value = true;
                }else{
                    ElMessage({
						message: res.msg||'获取用户信息失败.',
						type: "eror",
					});
                }
            });
    }

    

    // 不生效
    // const pwdVisible = ref(true);
    //pwdVisible.value = localStorage.getItem('userId')==editObj.form.id?false:true;


    const pwdVisible = computed(() => {
        return localStorage.getItem('userId')==editObj.form.id?false:true;
    });

    const realNameVisible = computed(() => {
        return editObj.form.realName =='Admin'?true:false;
    });

    // 修改模板配置
    const editUser = (formEl: FormInstance | undefined) => {

        if (!formEl) return;
        
        formEl.validate((valid) => {

            if(!valid) {
                return false;
            }

            // 禁用按钮
            editObj.submit_button_disabled = true;
            editObj.submit_button_loading = true;
            if(editObj.form.password){
                editObj.form.password = editObj.form.password.trim();
                editObj.form.password = desPwd.getDes(editObj.form.password, 'kingdom');
            }

            editObj.form.lastLoginTime = null;
            editObj.form.createdTime = null;
            editObj.form.updatedTime = null;

            UpdateUser(editObj.form)
            .then((res) => {
                if(res.code === 200){
                    editObj.submit_button_disabled = false;
                    editObj.submit_button_loading = false;
                    ElMessage({
                        message: '修改成功！',
                        type: 'success',
                    })
                    editDialogFormVisible.value = false;
                    queryList();
                }else{
                    ElMessage({
						message: res.msg||'修改用户信息失败.',
						type: "eror",
					});
                    editObj.submit_button_disabled = false;
                    editObj.submit_button_loading = false;
                }
            }).catch((error) => { 
                editObj.submit_button_disabled = false;
                editObj.submit_button_loading = false;
            });

        })



    }
    // 打开删除对话框
    const openDelDialog = (id) => {
        dataUser.id = id
        delDialogFormVisible.value=true
    } 
    // 删除模板配置
    const delUser = () => {
        delUserReq(dataUser)
            .then((res) => {
                if(res.code === 200){
                    ElMessage({
                        message: '删除成功！',
                        type: 'success',
                    })
                    delDialogFormVisible.value = false
                    queryList();
                }else{
                    ElMessage({
                        message: res.msg || '删除用户异常.',
                        type: 'error',
                    });
                }
                
            }).catch((error) => { });
    }
</script>

<style scoped></style>